package com.eleadmin.store.biz.impl;

import com.eleadmin.damon.utils.constant.UserConstant;
import com.eleadmin.damon.utils.results.BaseDao;
import com.eleadmin.damon.utils.results.PageResult2;
import com.eleadmin.damon.utils.utils.DateUtil;
import com.eleadmin.damon.utils.utils.Utils;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.store.biz.EntryBillBiz;
import com.eleadmin.store.entity.EntryBill;
import com.eleadmin.common.core.web.JsonResult;
import com.eleadmin.store.result.PriceResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * 数据层实现类
 *
 * @author : Doman
 * @version ：1.0
 * @date : 2024-02-14 14:59:02
 */
@Repository
public class EntryBillBizImpl extends BaseDao implements EntryBillBiz {

    @Override
    public JsonResult list(PageResult2<T> page, EntryBill entryBill, User loginUser) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<EntryBill> rm = new BeanPropertyRowMapper<EntryBill>(EntryBill.class);
        StringBuffer sql = new StringBuffer("select e.id,e.organization_id,e.code");
        sql.append(",e.supplier,e.entryTime,e.remark");
        sql.append(",e.unpaid,e.state,e.invoice,e.total,e.create_time");
        sql.append(",e.create_user,e.update_time,e.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName,suser2.nickname updateName ");
        sql.append(" from we_entry_bill e ");
        sql.append(" inner join sys_user suser on suser.user_id=e.create_user ");
        sql.append(" left join sys_user suser2 on suser2.user_id=e.update_user ");
        if(Utils.isNotEmpty(entryBill)) {
            if (Utils.isNotEmpty(entryBill.getSpecification()) || Utils.isNotEmpty(entryBill.getProductname())) {
                sql.append(" inner join we_entry_bill_son es on es.entryBillId=e.id ");
            }
        }
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=e.organization_id and sogzn.deleted=0 ");
        sql.append(" where e.deleted=0 ");
        if (loginUser.getUserId() != UserConstant.ADMIN_ID) {
            sql.append(" and e.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if (Utils.isNotEmpty(entryBill)) {
            if (Utils.isNotEmpty(entryBill.getSpecification())) {
                sql.append(" and instr(es.specification,:specification)>0 ");
                map.put("specification", entryBill.getSpecification());
            }
            if (Utils.isNotEmpty(entryBill.getProductname())) {
                sql.append(" and instr(es.productName,:productName)>0 ");
                map.put("productName", entryBill.getProductname());
            }
            if (Utils.isNotEmpty(entryBill.getKeywords())) {
                sql.append(" and instr(e.code,:keywords)>0 ");
                map.put("keywords", entryBill.getKeywords());
            }
            if (Utils.isNotEmpty(entryBill.getSupplier())) {
                sql.append(" and instr(e.supplier,:supplier)>0");
                map.put("supplier", entryBill.getSupplier());
            }
            if(Utils.isNotEmpty(entryBill.getDate1())){
                sql.append(" and e.entryTime>=:date1 ");
                map.put("date1", entryBill.getDate1() + " 00:00:00");
            }
            if(Utils.isNotEmpty(entryBill.getDate2())){
                sql.append(" and e.entryTime<=:date2 ");
                map.put("date2", entryBill.getDate2() + " 23:59:59");
            }
            if (Utils.isNotEmpty(entryBill.getState())) {
                sql.append(" and e.state=:state");
                map.put("state", entryBill.getState());
            }
            if (Utils.isNotEmpty(entryBill.getInvoice())) {
                sql.append(" and e.invoice=:invoice");
                map.put("invoice", entryBill.getInvoice());
            }
            if (Utils.isNotEmpty(entryBill.getSort()) && Utils.isNotEmpty(entryBill.getOrder())) {
                sql.append(" order by e." + entryBill.getSort() + " " + entryBill.getOrder());
            } else {
                sql.append(" order by e.create_time desc");
            }
        }
        return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
    }

    @Override
    public PriceResult entryBillNums(EntryBill entryBill, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<PriceResult> rm = new BeanPropertyRowMapper<PriceResult>(PriceResult.class);
        StringBuffer sql = new StringBuffer("select  ");
        sql.append(" ROUND(IFNULL(sum(e.unpaid),0),2) unpaid ");
        sql.append(" ,ROUND(IFNULL(sum(e.total),0),2) total ");
        sql.append(" from we_entry_bill e ");
        if(Utils.isNotEmpty(entryBill)) {
            if (Utils.isNotEmpty(entryBill.getSpecification()) || Utils.isNotEmpty(entryBill.getProductname())) {
                sql.append(" inner join we_entry_bill_son es on es.entryBillId=e.id ");
            }
        }
        sql.append(" where e.deleted=0 ");
        if (loginUser.getUserId() != UserConstant.ADMIN_ID) {
            sql.append(" and e.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if (Utils.isNotEmpty(entryBill)) {
            if (Utils.isNotEmpty(entryBill.getSpecification())) {
                sql.append(" and instr(es.specification,:specification)>0 ");
                map.put("specification", entryBill.getSpecification());
            }
            if (Utils.isNotEmpty(entryBill.getProductname())) {
                sql.append(" and instr(es.productName,:productName)>0 ");
                map.put("productName", entryBill.getProductname());
            }
            if (Utils.isNotEmpty(entryBill.getKeywords())) {
                sql.append(" and instr(e.code,:keywords)>0 ");
                map.put("keywords", entryBill.getKeywords());
            }
            if (Utils.isNotEmpty(entryBill.getSupplier())) {
                sql.append(" and instr(e.supplier,:supplier)>0");
                map.put("supplier", entryBill.getSupplier());
            }
            if(Utils.isNotEmpty(entryBill.getDate1())){
                sql.append(" and e.entryTime>=:date1 ");
                map.put("date1", entryBill.getDate1() + " 00:00:00");
            }
            if(Utils.isNotEmpty(entryBill.getDate2())){
                sql.append(" and e.entryTime<=:date2 ");
                map.put("date2", entryBill.getDate2() + " 23:59:59");
            }
            if (Utils.isNotEmpty(entryBill.getState())) {
                sql.append(" and e.state=:state");
                map.put("state", entryBill.getState());
            }
            if (Utils.isNotEmpty(entryBill.getInvoice())) {
                sql.append(" and e.invoice=:invoice");
                map.put("invoice", entryBill.getInvoice());
            }
            if (Utils.isNotEmpty(entryBill.getSort()) && Utils.isNotEmpty(entryBill.getOrder())) {
                sql.append(" order by e." + entryBill.getSort() + " " + entryBill.getOrder());
            } else {
                sql.append(" order by e.create_time desc");
            }
        }
        getMapParameter(sql, map);
        List<PriceResult> priceResults = jdbcTemplate.query(sql.toString(), map, rm);
        return Utils.isNotEmpty(priceResults)?priceResults.get(0): null;
    }

    @Override
    public List<EntryBill> list(EntryBill entryBill, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<EntryBill> rm = new BeanPropertyRowMapper<EntryBill>(EntryBill.class);
        StringBuffer sql = new StringBuffer("select e.id,e.organization_id,e.code");
        sql.append(",e.supplier,e.entryTime,e.remark");
        sql.append(",e.unpaid,e.state,e.invoice,e.total,e.create_time");
        sql.append(",e.create_user,e.update_time,e.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName ");
        sql.append(" from we_entry_bill e ");
        sql.append(" inner join sys_user suser on suser.user_id=e.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=e.organization_id and sogzn.deleted=0 ");
        if(Utils.isNotEmpty(entryBill)) {
            if (Utils.isNotEmpty(entryBill.getSpecification()) || Utils.isNotEmpty(entryBill.getProductname())) {
                sql.append(" inner join we_entry_bill_son es on es.entryBillId=e.id ");
            }
        }
        sql.append(" where e.deleted=0 ");
        if (loginUser.getUserId() != UserConstant.ADMIN_ID) {
            sql.append(" and e.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
        if (Utils.isNotEmpty(entryBill)) {
            if (Utils.isNotEmpty(entryBill.getSpecification())) {
                sql.append(" and instr(es.specification,:specification)>0 ");
                map.put("specification", entryBill.getSpecification());
            }
            if (Utils.isNotEmpty(entryBill.getProductname())) {
                sql.append(" and instr(es.productName,:productName)>0 ");
                map.put("productName", entryBill.getProductname());
            }
            if (Utils.isNotEmpty(entryBill.getKeywords())) {
                sql.append(" and instr(e.code,:keywords)>0 ");
                map.put("keywords", entryBill.getKeywords());
            }
            if (Utils.isNotEmpty(entryBill.getSupplier())) {
                sql.append(" and instr(e.supplier,:supplier)>0");
                map.put("supplier", entryBill.getSupplier());
            }
            if(Utils.isNotEmpty(entryBill.getDate1())){
                sql.append(" and e.entryTime>=:date1 ");
                map.put("date1", entryBill.getDate1() + " 00:00:00");
            }
            if(Utils.isNotEmpty(entryBill.getDate2())){
                sql.append(" and e.entryTime<=:date2 ");
                map.put("date2", entryBill.getDate2() + " 23:59:59");
            }
            if (Utils.isNotEmpty(entryBill.getState())) {
                sql.append(" and e.state=:state");
                map.put("state", entryBill.getState());
            }
            if (Utils.isNotEmpty(entryBill.getInvoice())) {
                sql.append(" and e.invoice=:invoice");
                map.put("invoice", entryBill.getInvoice());
            }
            if (Utils.isNotEmpty(entryBill.getSort()) && Utils.isNotEmpty(entryBill.getOrder())) {
                sql.append(" order by e." + entryBill.getSort() + " " + entryBill.getOrder());
            } else {
                sql.append(" order by e.create_time desc");
            }
        }
        getMapParameter(sql, map);
        return jdbcTemplate.query(sql.toString(), map, rm);
    }

    @Override
    public EntryBill getById(String id) {
        RowMapper<EntryBill> rm = new BeanPropertyRowMapper<EntryBill>(EntryBill.class);
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("select e.id,e.organization_id,e.code");
        sql.append(",e.supplier,e.entryTime,e.remark");
        sql.append(",e.unpaid,e.state,e.invoice,e.total,e.create_time");
        sql.append(",e.create_user,e.update_time,e.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.nickname createName ");
        sql.append(" from we_entry_bill e ");
        sql.append(" inner join sys_user suser on suser.user_id=e.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=e.organization_id and sogzn.deleted=0 ");
        sql.append(" where e.deleted=0 and e.id=:id ");
        map.put("id", id);
        getMapParameter(sql, map);
        try {
            return jdbcTemplate.queryForObject(sql.toString(), map, rm);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Integer save(EntryBill entryBill, User loginUser) {
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        KeyHolder keyHolder = new GeneratedKeyHolder();
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("insert into we_entry_bill (");
        sql.append("organization_id,code,supplier,entryTime");
        sql.append(",remark,unpaid,state,invoice");
        sql.append(",total,create_user,create_time) values ( ");
        sql.append(":organization_id,:code,:supplier,:entryTime");
        sql.append(",:remark,:unpaid,:state,:invoice");
        sql.append(",:total,:create_user,now())");
        map.put("organization_id", loginUser.getOrganizationId() + "");
        map.put("code", entryBill.getCode());
        map.put("supplier", entryBill.getSupplier());
        map.put("entryTime", entryBill.getEntrytime());
        map.put("remark", entryBill.getRemark());
        map.put("unpaid", entryBill.getUnpaid());
        map.put("state", entryBill.getState());
        map.put("invoice", entryBill.getInvoice());
        map.put("total", entryBill.getTotal());
        map.put("create_user", loginUser.getUserId() + "");
        getMapParameter(sql, map);
        int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
            @Override
            public boolean hasValue(String paramName) {
                return map.containsKey(paramName);
            }

            @Override
            public Object getValue(String paramName) throws IllegalArgumentException {
                return map.get(paramName);
            }
        }, generatedKeyHolder);

        Integer id = generatedKeyHolder.getKey().intValue();
        return id;
    }

    @Override
    public boolean update(EntryBill entryBill, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("update we_entry_bill set ");
        sql.append("supplier=:supplier,unpaid=:unpaid,entryTime=:entryTime ");
        sql.append(",remark=:remark,state=:state ");
        sql.append(",invoice=:invoice,total=:total,update_time=now() ");
        sql.append(",update_user=:update_user where id=:id ");
        map.put("supplier", entryBill.getSupplier());
        map.put("unpaid", entryBill.getUnpaid());
        map.put("entryTime", entryBill.getEntrytime());
        map.put("remark", entryBill.getRemark());
        map.put("state", entryBill.getState());
        map.put("invoice", entryBill.getInvoice());
        map.put("total", entryBill.getTotal());
        map.put("update_user", loginUser.getUserId() + "");
        map.put("id", entryBill.getId());
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean updateTableState(EntryBill entryBill, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("update we_entry_bill set ");
        sql.append("state=:state,invoice=:invoice,update_time=now() ");
        sql.append(",update_user=:update_user where id=:id ");
        map.put("state", entryBill.getState());
        map.put("invoice", entryBill.getInvoice());
        map.put("update_user", loginUser.getUserId() + "");
        map.put("id", entryBill.getId());
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean updateTotal(EntryBill entryBill, User loginUser) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sql = new StringBuffer("update we_entry_bill set ");
        sql.append("total=:total,update_time=now() ");
        sql.append(",update_user=:update_user where id=:id ");
        map.put("total", entryBill.getTotal());
        map.put("update_user", loginUser.getUserId() + "");
        map.put("id", entryBill.getId());
        getMapParameter(sql, map);
        int count = jdbcTemplate.update(sql.toString(), map);
        return count > 0;
    }

    @Override
    public boolean remove(String id, User loginUser) {
        int count = 0;
        Map<String, String> map = null;
        if (id.length() > 0) {
            for (String id1 : id.split(",")) {
                map = new HashMap<String, String>();
                if (id1 == null || id1.equals("")) {
                    break;
                }
                StringBuffer sql = new StringBuffer("update we_entry_bill set deleted=1" +
                        ",update_user=:update_user, update_time=now() "
                        + " where id =:id ");
                map.put("update_user", loginUser.getUserId() + "");
                map.put("id", id1);
                getMapParameter(sql, map);
                count = jdbcTemplate.update(sql.toString(), map);
            }
        }
        return count > 0;
    }
}
